import React, { Component } from 'react';
import styled from 'styled-components/native';
import { graphql, compose, withApollo } from 'react-apollo';
import { connect } from 'react-redux';
import { FlatList } from 'react-native';
import Touchable from '@appandflow/touchable';

import { setUserInfo } from '../actions/user';
import { toLoginScreen, toRegisterScreen } from '../actions/nav';
import { colors, dimens } from '../utils/constants';
import FeedCard from '../components/feeds/FeedCard';
import HeaderAvatar from '../components/HeaderAvatar';
import NewTweetActionButton from '../components/NewTweetActionButton';

import GET_TWEETS_QUERY from '../graphql/queries/getTweets';
import ME_QUERY from '../graphql/queries/me';
import TWEET_ADDED_SUBSCRIPTION from '../graphql/subscriptions/tweetAdded';
import TWEET_FAVOURITED_SUBSCRIPTION from '../graphql/subscriptions/tweetFavourited';

const Root = styled.View`
  width: 100%;
  backgroundColor: ${props => props.theme.BACKGROUND};
  flex: 1;
  alignItems: center;
  justifyContent: center;
  alignSelf: center;
`;

const BottomButtonContainer = styled.View`
  flexDirection: row;
  width: 100%;
  backgroundColor: ${ colors.WHITE };
  padding: ${ dimens.PADDING };
  alignItems: center;
  justifyContent: space-between;
  borderTopColor: ${ colors.DIVIDER };
  borderTopWidth: 1;
`;

const RegisterButton = styled(Touchable).attrs({
  feedback: 'opacity'
}) `
  width: 49%;
  height: 42;
  backgroundColor: ${ colors.WHITE };
  alignItems: center;
  justifyContent: center;
  borderRadius: 4;
  borderColor: ${ colors.DIVIDER };
  borderWidth: 1;
`;

const RegisterButtonText = styled.Text`
  fontSize: 18;
  color: ${ colors.PRIMARY }
`;

const LoginButton = RegisterButton.extend`
  backgroundColor: ${ colors.PRIMARY };
  borderColor: ${ colors.PRIMARY };
`;

const LoginButtonText = RegisterButtonText.extend`
  color: ${ colors.WHITE };
`;

class HomeScreen extends Component {

  static navigationOptions = () => {
    const headerLeft = <HeaderAvatar />;
    const headerRight = <NewTweetActionButton />;
    return {headerLeft, headerRight};
  };

  componentWillMount() {
    this.props.data.subscribeToMore({
      document: TWEET_ADDED_SUBSCRIPTION,
      updateQuery: (prev, { subscriptionData }) => {
        if (!subscriptionData.data) {
          return prev;
        }

        const newTweet = subscriptionData.data.tweetAdded;
        if (!prev.getTweets.find(item => item._id === newTweet._id)) {
          return {
            ...prev,
            getTweets: [{ ...newTweet }, ...prev.getTweets]
          }
        }

        return prev;
      }
    });

    this.props.data.subscribeToMore({
      document: TWEET_FAVOURITED_SUBSCRIPTION,
      updateQuery: (prev, { subscriptionData }) => {
        if(!subscriptionData.data) {
          return prev;
        }

        const newTweet = subscriptionData.data.tweetFavourited;
        return {
          ...prev,
          getTweets: prev.getTweets.map(item => {
            if (item._id === newTweet._id) {
              return {
                ...item,
                favouriteCount: newTweet.favouriteCount
              }
            }
            return item;
          })
        }
      }
    });
  }

  componentDidMount() {
    this.props.navigation.setParams({ isAuthenticated: this.props.isAuthenticated });
  }

  componentDidUpdate() {
    if (this.props.isAuthenticated) {
      this._getUserInfo();
    }
  }

  _getUserInfo = async () => {
    const { data: { me } } = await this.props.client.query({ query: ME_QUERY });
    this.props.setUserInfo(me);
  }

  _renderItem = ({ item }) => <FeedCard {...item} />

  _renderPlaceholder = () => <FeedCard placeholder isLoaded={this.props.data.loading} />

  render() {
    const { data } = this.props;
    if (data.loading) {
      return (
        <Root>
          <FlatList
            style={{ width: "100%" }}
            contentContainerStyle={{ alignSelf: "stretch" }}
            data={[1, 2, 3, 4, 5, 6]}
            keyExtractor={item => item}
            renderItem={this._renderPlaceholder}
          />
        </Root>
      );
    }

    return (
      <Root>
        <FlatList
          style={{ width: "100%" }}
          contentContainerStyle={{ alignSelf: "stretch" }}
          data={data.getTweets}
          keyExtractor={item => item._id}
          renderItem={this._renderItem}
        />
        {
          !this.props.isAuthenticated ?
          <BottomButtonContainer>
            <RegisterButton onPress={this.props.toRegisterScreen}>
              <RegisterButtonText>注册</RegisterButtonText>
            </RegisterButton>
            <LoginButton onPress={this.props.toLoginScreen}>
              <LoginButtonText>登录</LoginButtonText>
            </LoginButton>
          </BottomButtonContainer> : null
        }
      </Root>
    );
  }
}

const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  routes: state.nav.routes
})

export default withApollo(compose(
  connect(mapStateToProps, { setUserInfo, toLoginScreen, toRegisterScreen }),
  graphql(GET_TWEETS_QUERY)
)(HomeScreen));
